<?php
# $Id: listdir.php 21 2012-10-24 13:12:26Z trulec@gmail.com $
/**********************************************************************\
** ztListDir                                                            **
** Listet den Inhalt eines Verzeichnisses parametergesteuert auf        **
**                                                                      **
** Version 1.2                                                          **
** 20. Dezember 2002                                                    **
** Version 1.3                                                          **
** 09. May 2005                                                         **
** Version 1.4                                                          **
** 29. March 2007                                                       **
** Version 1.5                                                          **
** 16. February 2009                                                    **
** Version 1.6                                                          **
** 09. June 2011                                                        **
** Version 2.1                                                          **
** 28. June 2011                                                        **
** Version 2.2                                                          **
** 10. Juli 2011                                                        **
** Version 2.3                                                          **
** 24. Oktober 2012                                                     **
**                                                                      **
** Copyright (c) by Zeljko Trulec                                       **
** info@trulec.de                                                       **
** http://trulec.de                                                     **
**                                                                      **
** ==================================================================== **
** This program is free software. You can redistribute it and/or modify **
** it under the terms of the GNU General Public License as published by **
** the Free Software Foundation; either version 2 of the License.       **
\**********************************************************************/

/**********************************************************************\
** READ ME :                                                            **
**          + Just copy this file in any directory you wanna            **
**            shown as root-directory (with the subs in it)!            **
**          + Rename htaccess.txt to .htaccess                          **
**          + Maybe you want to change some parameters in listdir.php   **
**          + Enjoy the directory-listing!                              **
**                                                                      **
\**********************************************************************/
define('SECURITY_MEASURES_INCLUDES', 'justForInclusion');
define('DS', DIRECTORY_SEPARATOR);

// *** Konfigurationsdatei oder aehnliches einlesen (falls vorhanden)
define('INCLUDES_DIR_NAME', 'ztListDir_includes');
include_once '.' . DS . INCLUDES_DIR_NAME . DS . 'config.inc.php';
if(isset($PARAM["admin"]) && !empty($PARAM["admin"])) {
	foreach ($PARAM["admin"] as $key => $elem) {
		$PARAM["admin"][$key] = hash("sha256", $PARAM["admin"][$key]);
	}
}


// *** ***************************************************
// *** Parameter *****************************************
// *** ***************************************************
ini_set("display_errors", "stdout");
if (!session_start()) die("Session can't be started!");
define('APACHE_MIME_TYPES_URL', 'http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types');
define('APACHE_MIME_TYPES_DIR', '.' . DS . INCLUDES_DIR_NAME . DS);

// *** ***************************************************
// *** Versionsverwaltung
// *** ***************************************************
$PARAM["version_num"]  = "V2.3";
$PARAM["version_date"] = "24.10.2012";

// *** ***************************************************
// Pfade ermitteln
$PARAM["ztListDir_host"] = ( isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] != "off" ? "https://" : "http://" ) . $_SERVER['HTTP_HOST'];
$PARAM["show_dir"] = $_SERVER["REDIRECT_URL"];
$docPath = $_SERVER["DOCUMENT_ROOT"];
if (substr($docPath, -1) == DS) $docPath = substr($docPath, 0, -1);
$myPath = dirname(__FILE__);
if (substr($myPath, -1) == DS) $myPath = substr($myPath, 0, -1);
$PARAM["ztListDir_dir"] = str_replace( array( "\\", $docPath), array( "/", ""), $myPath );
$PARAM["ztListDir_host"] .= $PARAM["ztListDir_dir"];
$PARAM["ztListDir_root"] = $docPath . $PARAM["ztListDir_dir"];
$PARAM["show_dir"] = preg_replace("/^".str_replace("/", "\\/", $PARAM["ztListDir_dir"])."/i", "", $PARAM["show_dir"]);

// *** Header- und Footer-Dateien zur zusaetzlichen Ausgabe des HTML-Layouts
// *** wird nur benutzt, wenn $PARAM["include"] == 0 und die Dateien existieren
$PARAM["header"] = $self_path . DS . $PARAM["header"];
$PARAM["footer"] = $self_path . DS . $PARAM["footer"];

$ztListDirPath = $myPath . DS . INCLUDES_DIR_NAME;                                               // *** Pfad zum Ordner mit den Image- und Include-Dateien, ohne(!) abschliessendes /
$includesUrl = $PARAM["ztListDir_host"] . "/" . INCLUDES_DIR_NAME;      // *** URL zum Ordner mit den Image- und Include-Dateien, ohne(!) abschliessendes /
$imagesUrl = $includesUrl . "/" . "images";                                                       // *** URL zum Ordner mit den Images, bitte nicht aendern, da sonst das CSS nicht funktioniert
$diricon = '<img src="' . $imagesUrl . '/idir.gif" border="0">';                                 // *** Image fuer Ordner
$dupicon = '<img src="' . $imagesUrl . '/idirup.gif" border="0">';                               // *** Image fuer uebergeordneten Ordner

// *** ***************************************************
// *** Parameter anpassen (Pfade etc)
// *** ***************************************************
for($i=0,$n=count($icon); $i<$n; $i++) {
	if (!isset($icon[$i]) || !isset($icon[$i]["path"])) continue;
	$icon[$i]["path"] = $imagesUrl . "/" . $icon[$i]["path"];
}
$icon["default"] = $imagesUrl . "/" . $icon_default;
$icon["desc"] = $imagesUrl . "/" . $icon_desc;
unset($icon_default, $icon_desc);

$spacer  = $imagesUrl . '/spacer.gif';
$dnam = $_SERVER["DOCUMENT_ROOT"] . $_SERVER["REDIRECT_URL"];

// Dateien mit Passwoertern
$dnamPWFile1 = null;  // Ordner-Passwort
$dnamPWFile2 = null;  // Datei-Passwort
$metaRefresh = null;
if (is_file($dnam . "pass.dir")) $dnamPWFile1 = $dnam . "pass.dir";
if (is_file($dnam . ".pass.file")) $dnamPWFile2 = $dnam . ".pass.file";

array_push($PARAM["filesNoShow"], ".htaccess", ".file", ".dir", ".php");
array_push($PARAM["dirNoShow"], basename($ztListDirPath));
$PARAM["allowable_tags"] = '<br><a><b><i><u><ul><ol><li><h1><h2><h3><small><span>';
$PARAM["securityElements"] = array(".php", ".file", ".dir", ".htaccess", basename($ztListDirPath));

// ************************************************************************
// ************************************************************************
// Session-Reset
if (isset($_GET["clean"])) {
	unset($_SESSION["ztListDir"]);
	session_destroy();
	ZTLD::redir2self();
}
if (isset($_GET["logout"])) {
	ZTLD::logOff();
	ZTLD::redir2self();
}

if (!empty($_GET["a"]) && $_GET["a"] == "makeMimeFile") {
	if (ZTLD::isUser()) {
		if (ZTLD::makeMimeArrayFile()) ZTLD::setMessage("Mime file successful created.");
		else ZTLD::setError("Error creating mime file.");
		ZTLD::redir2self();
	}
	else {
		ZTLD::setError("Access denied. You have to login and try it again (E36).");
		ZTLD::redir2self();
	}
}

// Security-Check
if (ZTLD::a_search(basename($dnam), $PARAM["securityElements"])) {
	ZTLD::show404($PARAM["ztListDir_dir"] . $PARAM["show_dir"]);
}

// Security-Check protected parent directories
if ($PARAM["pass"] && !ZTLD::isUser()) {
	$parentProtected = ZTLD::getProtectedParentFolder();
	if (!empty($parentProtected)) {
		foreach ($parentProtected as $parent) {
			$bFile = ZTLD::gID(dirname($parent)."/".basename($parent));
			if (!isset($_SESSION["ztListDir"]["downfile"][$bFile])) {
				ZTLD::setError("Access denied. Secret phrase is required (E34).");
				ZTLD::redir2self($PARAM["ztListDir_host"] . str_replace($PARAM["ztListDir_root"], "", dirname($parent)));
				break;
			}
		}
	}
}

// Sortierreihenfolge
if (isset($_GET["do"]) && $_GET["do"] >= 1 && $_GET["do"] <= 6 ) {
	$PARAM["displayOrder"] = $_GET["do"];
	$_SESSION["ztListDir"]["do"] = $_GET["do"];
	unset($_GET["do"]);
}
elseif (isset($_SESSION["ztListDir"]["do"]) && $_SESSION["ztListDir"]["do"] != "" && $_SESSION["ztListDir"]["do"] > 0) {
	$PARAM["displayOrder"] = $_SESSION["ztListDir"]["do"];
}
// ************************************************************************
// ************************************************************************


// ************************************************************************
// ************************************************************************
// Passworteingaben checken
if ($PARAM["pass"]) {
	
	// check given username & password OR
	// filedownload && password OR
	// protection and unprotection of dir or file
	if (!empty($_POST)) {
		
		// ************************************
		// protected memberarea
		if (isset($_POST["username"])) {
			
			// error
			if (preg_replace("[a-zA-Z0-9]", "", $_POST["username"]) !== $_POST["username"]
					|| strlen($_POST["username"]) == 0
					|| !isset($_POST["secword"])
					|| strlen($_POST["secword"]) != 64) {
				ZTLD::setError("There is an error occured on decoding the username or secret phrase (E39).");
				ZTLD::redir2self();
			}
			
			elseif (!isset($PARAM["admin"])
							|| !isset($PARAM["admin"][$_POST["username"]])
							|| strcasecmp($PARAM["admin"][$_POST["username"]], $_POST["secword"]) !== 0) {
				ZTLD::setError("Youre username or secret phrase for this area is incorrect (E17).");
				ZTLD::redir2self();
			}
			
			// ... successed
			$_SESSION["ztListDir"]["user"][$_POST["username"]] = $_POST["secword"];
			ZTLD::redir2self();
		}
		
		// ************************************
		// protect dir or file
		elseif (isset($_POST["lockfile"])) {
			if (ZTLD::isUser()) {
				if(!empty($_POST["lockfile"])) {
					
					// unprotect the dir or file
					if (isset($_POST["secword"]) && !empty($_POST["secword"]) && $_POST["secword"] == "unlock") {
						$dnamPWFile1 = $dnam . $_POST["lockfile"] . "/pass.dir";
						$dnamPWFile2 = $dnam . $_POST["lockfile"] . ".pass.file";
						if (is_file($dnamPWFile1)) {
							if (unlink($dnamPWFile1)) ZTLD::setMessage("Unprotecting object '" . $_POST["lockfile"] . "' successful");
							else ZTLD::setError("Unprotecting object '" . $_POST["lockfile"] . "' failed (E52)");
						}
						elseif (is_file($dnamPWFile2)) {
							if (unlink($dnamPWFile2)) ZTLD::setMessage("Unprotecting object '" . $_POST["lockfile"] . "' successful");
							else ZTLD::setError("Unprotecting object '" . $_POST["lockfile"] . "' failed (E53)");
						}
					}
					
					// protect the dir or file
					elseif (isset($_POST["secword"]) && !empty($_POST["secword"]) && strlen($_POST["secword"]) == 64) {
						$dnamPWFile1 = $dnam . $_POST["lockfile"] . "/pass.dir";
						$dnamPWFile2 = $dnam . $_POST["lockfile"] . ".pass.file";
						if (is_dir($dnam . $_POST["lockfile"])) {
							if (file_put_contents($dnamPWFile1, $_POST["secword"]) === false) ZTLD::setError("Protecting object '" . $_POST["lockfile"] . "' failed (E54)");
							else ZTLD::setMessage("Protecting object '" . $_POST["lockfile"] . "' successful");
							ZTLD::redir2self();
						}
						elseif (is_file($dnam . $_POST["lockfile"])) {
							if (file_put_contents($dnamPWFile2, $_POST["secword"]) === false) ZTLD::setError("Protecting object '" . $_POST["lockfile"] . "' failed (E55)");
							else ZTLD::setMessage("Protecting object '" . $_POST["lockfile"] . "' successful");
							ZTLD::redir2self();
						}
						else ZTLD::show404();
					}
					else ZTLD::show404();
				}
				else ZTLD::show404();
			}
			else ZTLD::show404();
		}
		
		// ************************************
		// download error
		elseif (!isset($_POST["downfile"]) || empty($_POST["downfile"]) || !isset($_POST["secword"]) || strlen($_POST["secword"]) != 64) {
			ZTLD::setError("There is an error occured on decoding the secret phrase, file or directory (E37).");
			ZTLD::redir2self();
		}
		
		// ************************************
		// access protected dir or file
		else {
			
			// Protected file or dir
			$bFile = ZTLD::gID($dnam . basename($_POST["downfile"]));
			$_SESSION["ztListDir"]["downfile"][$bFile]["pass"] = $_POST["secword"];
			$_SESSION["ztListDir"]["downfile"][$bFile]["file"] = $dnam . basename($_POST["downfile"]);
			$dnamPWFile1 = $dnam . basename($_POST["downfile"]) . "/pass.dir";
			$dnamPWFile2 = $dnam . basename($_POST["downfile"]) . ".pass.file";
			
			// protected directory
			if (is_dir($dnam . basename($_POST["downfile"])) && is_file($dnamPWFile1)) {
				
				// check password
				$secword = file_get_contents($dnamPWFile1);
				
				// ... failed
				if (strcasecmp($secword, $_SESSION["ztListDir"]["downfile"][$bFile]["pass"]) !== 0) {
					ZTLD::setError("The secret phrase for this directory is incorrect (E16).");
					unset($_SESSION["ztListDir"]["downfile"][$bFile]);
					ZTLD::redir2self();
				}
				
				// ... successed -> redir 2 directory
				else {
					#die($PARAM["ztListDir_dir"] . $PARAM["show_dir"] . basename($_POST["downfile"]));
					ZTLD::redir2self($PARAM["ztListDir_dir"] . $PARAM["show_dir"] . basename($_POST["downfile"]));
				}
			}
			
			// protected file
			elseif (is_file($dnam . basename($_POST["downfile"])) && is_file($dnamPWFile2)) {
				
				// check password
				$secword = file_get_contents($dnamPWFile2);
				
				// ... failed
				if (strcasecmp($secword, $_SESSION["ztListDir"]["downfile"][$bFile]["pass"]) !== 0) {
					ZTLD::setError("The secret phrase for this file is incorrect (E15).");
					unset($_SESSION["ztListDir"]["downfile"][$bFile]);
					ZTLD::redir2self();
				}
				
				// ... successed -> redir 2 download
				else {
					$_SESSION["ztListDir"]["metarefresh"] = $PARAM["ztListDir_dir"] . $PARAM["show_dir"] . basename($_POST["downfile"]);
					ZTLD::redir2self($PARAM["ztListDir_dir"] . $PARAM["show_dir"]);
				}
			}
			else {
				ZTLD::show404($_POST["downfile"]);
//				ZTLD::setError("There is an error occured on decoding the file or directory (E38).");
//				unset($_SESSION["ztListDir"]["downfile"][$bFile]);
//				ZTLD::redir2self();
			}
		}
	}
	
	// redir to download
	if (isset($_SESSION["ztListDir"]["metarefresh"]) && !empty($_SESSION["ztListDir"]["metarefresh"])) {
		$metaRefresh  = '<meta http-equiv="refresh" content="1; URL='.$_SESSION["ztListDir"]["metarefresh"].'">';
		$metaRefresh .= "\n<script type=\"text/javascript\">waitAndEffekt('#downhint');</script>";
		unset($_SESSION["ztListDir"]["metarefresh"]);
	}
}
// ************************************************************************
// ************************************************************************




// ************************************************************************
// ************************************************************************
// Ist es eine Datei?
if (is_file($dnam)) {
	
	// Passwortabfrage und keine Datei im eigenen include-Ordner?
	if ($PARAM["pass"]
			&& !is_file($ztListDirPath . "/" . basename($dnam))
			&& !is_file($ztListDirPath . "/images/" . basename($dnam))
			&& !ZTLD::isUser()) {
		
		$bFile = ZTLD::gID($dnam);
		// Passwort wurde nicht eingegeben
		if (!is_null($dnamPWFile2) && !isset($_SESSION["ztListDir"]["downfile"][$bFile])) {
			ZTLD::setError("Access denied. Secret phrase is required (E33).");
			ZTLD::redir2self(dirname($PARAM["ztListDir_dir"] . $PARAM["show_dir"]));
		}
		
		// Passwort wurde eingegeben - also download
		else ZTLD::fileDownload($dnam);
	}
	
	// Datei zum normalen Download ausgeben
	else ZTLD::fileDownload($dnam);
}

// Wenn es auch kein Ordner ist, dann ist der Pfad nicht vorhanden!
elseif (!is_dir($dnam)) ZTLD::show404($PARAM["ztListDir_dir"] . $PARAM["show_dir"]);

// Passwortabfrage beim Ordner?
elseif ($PARAM["pass"] && !ZTLD::isUser()) {
	$bFile = ZTLD::gID(dirname($dnam)."/".basename($dnam));
	
	// Passwort-Datei vorhanden aber keins eingegeben (gespeichert)
	if (!is_null($dnamPWFile1) && !isset($_SESSION["ztListDir"]["downfile"][$bFile])) {
		ZTLD::setError("Access denied. Secret phrase is required (E35).");
		ZTLD::redir2self(dirname($PARAM["ztListDir_dir"] . $PARAM["show_dir"]));
	}
}
// ************************************************************************
// ************************************************************************


if (!file_exists(APACHE_MIME_TYPES_DIR . "mime.types.inc.php")) {
	ZTLD::setError("'mime.types' file is missing, you have to login and create it (E61).");
}


// ************************************************************************
// ************************************************************************
// *** HTML Grundaussehen
if (!$PARAM["include"]) {
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<title><?php echo $PARAM["ztListDir_host"] . $PARAM["show_dir"] ?> | <?php echo $PARAM["html_title"]; ?></title>
<?php } ?>
	<script type="text/javascript" src="<?php echo $includesUrl; ?>/jquery-1.6.1.min.js"></script>
	<script type="text/javascript" src="<?php echo $includesUrl; ?>/jquery-ui-ztlistdir.min.js"></script>
	<script type="text/javascript" src="<?php echo $includesUrl; ?>/jquery.sha256.min.js"></script>
	<script type="text/javascript" src="<?php echo $includesUrl; ?>/ztListDir.min.js"></script>
	<link rel="stylesheet" href="<?php echo $includesUrl; ?>/jquery-ui-ztlistdir.css" type="text/css">
	<link rel="stylesheet" href="<?php echo $includesUrl; ?>/main_css.css" type="text/css">
<?php
if (!$PARAM["include"]) {
	echo '
</head>
<body>';
	if (is_file($PARAM["header"])) {
		include($PARAM["header"]);
	}
} ?>

<?php echo $metaRefresh; ?>

<table border="0" width="<?php echo $PARAM["width"]?>" align="center" cellpadding="2" cellspacing="0" class="maintab ui-widget">
<tr><td><img src="<?php echo $spacer ?>" width="1" height="5" border="0"></td></tr>
<tr>
	<td class="title ui-widget-header">
		<h2 style="float: left;"><b><?php echo $PARAM["html_title"]; ?></b></h2>
<?php if ($PARAM["pass"]) { ?>
		<div id="buttonKillSession" class="icon-right ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only" title="restart a clean session">
			<a href="?clean">
				<span class="ui-button-icon-primary ui-icon ui-icon-trash">&nbsp;</span>
				<span class="ui-button-text">&nbsp;</span>
			</a>
		</div>
		
	<?php if (!isset($_SESSION["ztListDir"]["user"]) || empty($_SESSION["ztListDir"]["user"])) { ?>
		<div id="buttonGoMember" class="icon-right" title="login" style="display: none;">&nbsp;</div>
	<?php } else {
		// Benutzerfunktionen ?>
		<div id="buttonMemberMakeMime" class="icon-right" title="make mime file" style="display: none;">&nbsp;</div>
		<div id="buttonGoMemberExit" class="icon-right" title="logout" style="display: none;">&nbsp;</div>
		<?php if ($PARAM["show_username"]) { ?>
		<div class="text-right username" title="currently logged in"><?php echo ZTLD::getUsername(); ?></div>
		<?php } ?>
	<?php }
	} ?>
	</td>
</tr>
<tr>
	<td class="minitab ui-widget-content" style="border-top: 0; border-bottom: 0;">
		<?php
		if ($PARAM["pass"]) {
		?>
		<div id="jsHint" class="container ui-state-highlight ui-corner-all">
			<span class="ui-icon ui-icon-info" style="float: left; margin-right: .3em;"></span>
			<b>Javascript is disabled on your browser.</b><br />
			Please enable JavaScript to use the feature "protected content".
		</div>
		
		<?php
		}
		if (ZTLD::isError()) {
			$err = ZTLD::getError(true); ?>
			<div class="container ui-state-error ui-corner-all">
				<p>
					<span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span>
					<b>Alert:</b> <?php echo $err; ?>
				</p>
			</div>
<?php
		}
		if (ZTLD::isMessage()) {
			$msg = ZTLD::getMessage(true); ?>
			<div class="container ui-state-highlight ui-corner-all">
				<p>
					<span class="ui-icon ui-icon-info" style="float: left; margin-right: .3em;"></span>
					<?php echo $msg; ?>
				</p>
			</div>
<?php
		}
		if (!empty($metaRefresh)) {
?>
			<div id="downhint" class="container ui-state-highlight ui-corner-all">
				<p>
					<span class="ui-icon ui-icon-info" style="float: left; margin-right: .3em;"></span>
					<b>Download</b> will start shortly.
				</p>
			</div>
<?php
		}
		
		ZTLD::getDirList($dnam);
		?>
	</td>
</tr>
<tr><td class="footer ui-state-active"><img src="<?php echo $spacer ?>" width="1" height="5" border="0"></td></tr>
</table>
<br>
<div align="center"><div style="width: <?php echo $PARAM["width"]?>;">
	<div style="text-align: right; font-size: 9px; font-weight: bold;">Servertime: <?php echo date("d.m.Y H:i:s"); ?></div>
</div></div>
<div align="center"><div style="width: <?php echo $PARAM["width"]?>;">
	<div align="center" style="border-top: 3px double black; font-size: 9px;"><b>ztListDir <?php echo $PARAM["version_num"]; ?></b> (<?php echo $PARAM["version_date"]; ?>) &nbsp; | &nbsp; &copy; 2002-<?php echo date("Y"); ?> by Z. Trulec &nbsp; | &nbsp; http://trulec.de</div>
</div></div>

<?php if ($PARAM["pass"]) { ?>
<div id="dialogsecretform" title="Secret phrase">
	<p><span id="description">The file or directory is protected:</span><br />
	<span class="validateTips">&nbsp;</span></p>

	<form action="" class="frmDialogsecretform" method="post" onsubmit="return checkForm('#dialogsecretform');">
		<input type="hidden" name="downfile" id="downfile" value="">
		<input type="hidden" name="secword" id="secword" value="">
		
		<div id="row1">
			<div><b>Object</b></div>
			<span id="downfilename"></span>
		</div>
		<div id="row2">
			<div><b>Secret phrase</b></div>
			<span><input type="password" id="secretword" value="" class="text ui-widget-content ui-corner-all" style="width: 100%;" /></span>
		</div>
	</form>
</div>

<div id="dialogsecretform2" title="Secret phrase">
	<p>This area is protected:<br />
	<span class="validateTips">&nbsp;</span></p>

	<form action="" class="frmDialogsecretform" method="post" onsubmit="return checkForm('#dialogsecretform2');">
		<input type="hidden" name="secword" id="secword" value="">
		
		<div id="row1">
			<div><b>Username</b></div>
			<span><input type="text" name="username" id="username" value="" class="text ui-widget-content ui-corner-all" style="width: 100%;" /></span>
		</div>
		<div id="row2">
			<div><b>Secret phrase</b></div>
			<span><input type="password" id="secretword" value="" class="text ui-widget-content ui-corner-all" style="width: 100%;" /></span>
		</div>
		<input type="submit" value="" style="display: none;">
	</form>
</div>
<?php

	if (ZTLD::isUser()) {
?>
<div id="dialogsecretform3" title="Secret phrase">
	
	<form action="" id="frm1" class="frmDialogsecretform" method="post" onsubmit="return checkLockForm();" style="display: none;">
	
		<p>To lock the directory or file, simply enter the secret phrase.<br />
		<span class="validateTips">&nbsp;</span></p>

		<input type="hidden" name="lockfile" id="lockfile1" value="">
		<input type="hidden" name="secword" id="secword" value="">
		
		<div id="row1">
			<div><b>Object</b></div>
			<span id="lockfilename1"></span>
		</div>
		<div id="row2">
			<div><b>Secret phrase</b></div>
			<span><input type="password" id="secretword" value="" class="text ui-widget-content ui-corner-all" style="width: 100%;" /></span>
		</div>
		<input type="submit" value="" style="display: none;">
	</form>
	
	<form action="" id="frm2" class="frmDialogsecretform" method="post" onsubmit="return checkLockForm();" style="display: none;">
	
		<p>You want to remove the protection?<br />
		<span class="validateTips">&nbsp;</span></p>

		<input type="hidden" name="lockfile" id="lockfile2" value="">
		<input type="hidden" name="secword" id="secword" value="">
		
		<div id="row1">
			<div><b>Object</b></div>
			<span id="lockfilename2"></span>
		</div>
		<input type="submit" value="" style="display: none;">
	</form>
	
</div>

<?php
	}
}

// ************************


if (!$PARAM["include"]) {
	if (is_file($PARAM["footer"])) {
		include($PARAM["footer"]);
	}
	echo '
</body>
</html>';
}








/**
 * Toolfunctions for ztListDir
 *
 * @author Zeljko Trulec
 * @copyright Zeljko Trulec
 */
class ZTLD {
	
	/**
	 * Enter description here ...
	 *
	 * @param string $dirName
	 */
	public static function getDirList ($dirName) {
		global $self_path, $icon, $diricon, $dupicon, $PARAM, $spacer;
		$dirName = realpath($dirName);
		$d = dir($dirName);
		$fullpath = str_replace( "\\", "/", $d->path );
		$dpath = str_replace( array("\\", $_SERVER["DOCUMENT_ROOT"]) , array("/", ""), $d->path );
		if( $dpath{strlen($dpath)-1} == "/" ) $dpath = substr( $dpath, 0, -1 );
		$gi = 0; // global counter
		$di = 0; // dir counter
		$fi = 0; // file counter
		$dirs = array();
		$fils = array();
		$d_anz = 0;
		$f_anz = 0;
		#$isRoot = str_replace($PARAM["ztListDir_user"], "", $dpath) == "/public/" ? true : false ;
		$isRoot = $PARAM["ztListDir_root"] == $fullpath ? true : false ;
		
		$w[0] = 25;
		if ($PARAM["show_dt"]) {
			$w[2] = 150;
		}
		else $w[2] = 5;
		if ($PARAM["show_sz"]) {
			$w[1] = (int)( ($PARAM["width"] - 60 - $w[2]) / 100 * 80 );
			$w[3] = (int)( ($PARAM["width"] - 60 - $w[2]) / 100 * 20 );
			$cs = 4;
		}
		else {
			$w[1] = (int)( $PARAM["width"] - 60 - $w[2] );
			$cs = 3;
		}
		
		// *** Path-Navi
		$pathNavi = '<td width="' . $w[0] . '">
<div id="buttonNaviHome" rootPath="' . $PARAM["ztListDir_host"] . '" class="icon-left ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only" title="jump to root">
	<a href="' . $PARAM["ztListDir_host"] . '">
		<span class="ui-button-icon-primary ui-icon ui-icon-home">&nbsp;</span>
		<span class="ui-button-text">&nbsp;</span>
	</a>
</div></td>
<td width="' . ($w[1]+$w[2]+$w[3]) . '" valign="middle" colspan="' . $cs . '">
	<div class="ui-corner-all navi">' . ZTLD::getNavi($dpath, $_SERVER['HTTP_HOST']) . '</div></td>';
		
		$dirs[$di++] = '<tr class="path-navi">' . $pathNavi . '</tr>';
		$dirs[$di++] = '<tr><td colspan="' . $cs . '"><img src="' . $spacer . '" width="1" height="10" border="0"></td></tr>';
		
		// *** Ueberschrift
		$class = "";
		if ($PARAM["displayOrder"]==1) $class = "orderDown";
		if ($PARAM["displayOrder"]==4) $class = "orderUp";
		$linkH = '?do='.($PARAM["displayOrder"]==1?4:1).'';
		$tmp = '<tr class="header"><td width="' . $w[0] . '">&nbsp;</td><td class="hover" onclick="window.location.href=\''.$dpath.'/'.$linkH.'\'"><a class="'.$class.'" href="'.$dpath.'/'.$linkH.'">Name</a></td>';
	
		$class = "";
		if ($PARAM["displayOrder"]==2) $class = "orderDown";
		if ($PARAM["displayOrder"]==5) $class = "orderUp";
		$linkH = '?do='.($PARAM["displayOrder"]==2?5:2).'';
		if ($PARAM["show_dt"]) $dordH = '<td nowrap="nowrap" class="hover timestamp" onclick="window.location.href=\''.$dpath.'/'.$linkH.'\'"><a class="'.$class.'" href="'.$dpath.'/'.$linkH.'">Datum</a></td>';
		else $dordH = "<td>&nbsp;</td>";
	
		$class = "";
		if ($PARAM["displayOrder"]==3) $class = "orderDown";
		if ($PARAM["displayOrder"]==6) $class = "orderUp";
		$linkH = '?do='.($PARAM["displayOrder"]==3?6:3).'';
		if ($PARAM["show_sz"]) $fordH = '<td class="hover size" onclick="window.location.href=\''.$dpath.'/'.$linkH.'\'"><a class="'.$class.'" href="'.$dpath.'/'.$linkH.'">Gr&ouml;&szlig;e</a></td>';
		else $fordH = "";
	
		#echo "$dpath<br />";
		if ($PARAM["order"]==2) $tmp .= $fordH . $dordH;
		else $tmp .= $dordH . $fordH;
		$dirs[$di++] = $tmp . '</tr>';
		#$gi++;
		unset($tmp);
	
	
		// *** Verzeichnis-Beschreibung
		$dirdesc = false;
		if( file_exists( $fullpath."/desc.dir" ) ) {
			$dirdesc = join("", file($fullpath."/desc.dir"));
		}
	
		$entryArr = array();
		$entryFile = array();
		$entryDir = array();
		while($entry = $d->read()) {
			if ($entry == "." || $entry == ".." || $entry == "desc.dir" || stripos($entry, ".file")) continue;
			$entryTmp["name"]     = $entry;
			$entryTmp["type"]     = "";
			$entryTmp["fullPath"] = $fullpath."/".$entry;
			$entryTmp["dt"]       = filemtime($entryTmp["fullPath"]);
			
			if (is_dir($dirName."/".$entry)) {
				$entryTmp["type"] = "d";
				$entryTmp["sz"] = null;
				$entryDir[] = $entryTmp;
			}
			else {
				$entryTmp["type"] = "f";
				$entryTmp["sz"] = self::get_Size( $entryTmp["fullPath"], $PARAM["sz_format"]);
				$entryFile[] = $entryTmp;
			}
			unset($entryTmp);
			$entryArr[] = $entry;
		}
		$d->close();
		
		if (count($entryDir)) usort($entryDir, array("ZTLD", "a_sort"));
		if (count($entryFile)) usort($entryFile, array("ZTLD", "a_sort"));
	
		// Ordner
		if (count($entryDir)) {
			foreach( $entryDir as $entry ) {
				$passSymb = null;
				$dnamPWFile = null;
				if (is_file($fullpath.'/'.$entry["name"].'/pass.dir')) $dnamPWFile = $fullpath.'/'.$entry["name"].'/pass.dir';
				$onClick = ' onclick="javascript:window.location.href=\''.$entry["name"].'\'"';
				$lockIcon = null;
				if ($PARAM["pass"] && self::isUser()) {
					$lockIcon = '<span title="protect directory" onclick="lockForm(\''.$entry["name"].'\', 1);" class="icon-left ui-icon-red ui-icon ui-icon-locked">&nbsp;</span>';
					if (!is_null($dnamPWFile)) $lockIcon = '<span title="remove directory protection" onclick="lockForm(\''.$entry["name"].'\', 2);" class="icon-left ui-icon-red ui-icon ui-icon-unlocked">&nbsp;</span>';
				}
				if ($PARAM["pass"] && !is_null($dnamPWFile)) {
					if ($PARAM["pass_icon"]) $passSymb = '<span class="'.($PARAM["pass_icon"]==1?'icon-left':'icon-right').' ui-icon ui-icon-locked"></span>';
					$onClick = " onclick=\"javascript:return dFileSW('".$entry["name"]."')\"";
					if (isset($_SESSION["ztListDir"]["downfile"][ZTLD::gID($fullpath.$entry["name"])]) || self::isUser()) {
						if ($PARAM["pass_icon"]) $passSymb = '<span class="'.($PARAM["pass_icon"]==1?'icon-left':'icon-right').' ui-icon ui-icon-unlocked"></span>';
						$onClick = ' onclick="javascript:window.location.href=\''.$entry["name"].'\'"';
					}
				}
				if (self::a_search($entry["name"], $PARAM["dirNoShow"])) continue;
				if ($PARAM["show_sz"]) $ford = '<td width="' . $w[3] . '" class="size">&nbsp;</td>';
				else $ford = "";
				if ($PARAM["show_dt"]) $dord = '<td width="' . $w[2] . '" class="timestamp" nowrap="nowrap">'.date("d.m.Y H:i:s",$entry["dt"]).'</td>';
				else $dord = "<td>&nbsp;</td>";
				$tmp = '<tr class="line_' . ((($gi)%2)?"odd":"even") . ' hover"><td'.$onClick.' width="' . $w[0] . '"><a href="'.$entry["name"].'/"'.$onClick.' border="0">'.$diricon.'</a></td><td width="' . $w[1] . '">'.$lockIcon.'<div'.$onClick.' class="fullheight"><a href="'.$entry["name"].'/"'.$onClick.'>'.($PARAM["pass_icon"]==1?$passSymb:null).'<span class="'.($PARAM["pass"]?'text-left':null).'">'.$entry["name"].'</span>'.($PARAM["pass_icon"]==2?$passSymb:null).'</a></div></td>';
				if ($PARAM["order"]==2) $tmp .= $ford . $dord;
				else $tmp .= $dord . $ford;
				$dirs[$di++] = $tmp . '</tr>';
				$d_anz++;
				$gi++;
			}
		}
		
		// Dateien
		if (count($entryFile)) {
			$last_entry=null;
			foreach( $entryFile as $entry ) {
				
				// Datei-Beschreibung der vorigen Datei
				if( !empty($last_entry) && file_exists( $fullpath."/".$last_entry.".file" ) ) {
					$filedesc = join( "", file( $fullpath."/".$last_entry.".file" ) );
					$f_desc = "\n".'<tr class="desc line_' . ((($gi)%2)?"even":"odd") . '"><td align="center" valign="top" width="' . $w[0] . '"><img src="' . $icon["desc"] . '" border="0" alt="Beschreibung zu ' . $last_entry . '"></td><td colspan="' . ($cs-1) . '" class="filedesc">' . nl2br(strip_tags($filedesc, $PARAM["allowable_tags"])) . "</td></tr>\n";
					$f_desc .= '<tr><td colspan="' . $cs . '"><img src="' . $spacer . '" width="1" height="6" border="0"></td></tr>';
					$fils[$fi++] = $f_desc;
				}
				$last_entry = $entry["name"];
				
				// aktuelle Datei
				$passSymb = null;
				$onClick = ' onclick="javascript:window.location.href=\''.$entry["name"].'\'"';
				$dnamPWFile = null;
				if (is_file($fullpath.'/'.$entry["name"].'.pass.file')) $dnamPWFile = $fullpath.'/'.$entry["name"].'.pass.file';
				$lockIcon = null;
				if ($PARAM["pass"] && self::isUser()) {
					$lockIcon = '<span title="protect file" onclick="lockForm(\''.$entry["name"].'\', 1);" class="icon-left ui-icon-red ui-icon ui-icon-locked">&nbsp;</span>';
					if (!is_null($dnamPWFile)) $lockIcon = '<span title="remove file protection" onclick="lockForm(\''.$entry["name"].'\', 2);" class="icon-left ui-icon-red ui-icon ui-icon-unlocked">&nbsp;</span>';
				}
				if ($PARAM["pass"] && !is_null($dnamPWFile)) {
					if ($PARAM["pass_icon"]) $passSymb = '<span class="'.($PARAM["pass_icon"]==1?'icon-left':'icon-right').' ui-icon ui-icon-locked"></span>';
					$onClick = " onclick=\"javascript:return dFileSW('".$entry["name"]."')\"";
					if (isset($_SESSION["ztListDir"]["downfile"][ZTLD::gID($fullpath.$entry["name"])]) || self::isUser()) {
						if ($PARAM["pass_icon"]) $passSymb = '<span class="'.($PARAM["pass_icon"]==1?'icon-left':'icon-right').' ui-icon ui-icon-unlocked"></span>';
						$onClick = ' onclick="javascript:window.location.href=\''.$entry["name"].'\'"';
					}
				}
				if (self::a_search($entry["name"], $PARAM["filesNoShow"])) continue;
				if ($PARAM["show_sz"]) $ford = '<td width="' . $w[3] . '" class="size" nowrap="nowrap">'.self::get_Size( $entry["fullPath"], $PARAM["sz_format"]).'</td>'."\n";
				else $ford = "";
				if ($PARAM["show_dt"]) $dord = '<td width="' . $w[2] . '" class="timestamp" nowrap="nowrap">'.date( "d.m.Y H:i:s", $entry["dt"] ).'</td>'."\n";
				else $dord = "<td>&nbsp;</td>\n";
				
				//$tmp = '<tr onclick="window.location.href=\''.$entry["name"].'\'" class="line_' . ((($gi)%2)?"odd":"even") . ' hover"><td width="' . $w[0] . '"><a href="'.$entry["name"].'" border="0">'.self::getIcon($entry["name"]).'</a></td><td width="' . $w[1] . '"><a href="'.$entry["name"].'">'.$entry["name"].' '.$passSymb.'</a></td>'."\n";
				$tmp = '<tr class="line_' . ((($gi)%2)?"odd":"even") . ' hover"><td'.$onClick.' width="' . $w[0] . '"><a href="'.$entry["name"].'"'.$onClick.' border="0">'.self::getIcon($entry["name"]).'</a></td><td width="' . $w[1] . '">'.$lockIcon.'<div'.$onClick.' class="fullheight"><a href="'.$entry["name"].'"'.$onClick.'>'.($PARAM["pass_icon"]==1?$passSymb:null).'<span class="'.($PARAM["pass"]?'text-left':null).'">'.$entry["name"].'</span>'.($PARAM["pass_icon"]==2?$passSymb:null).'</a></div></td>'."\n";
				if ($PARAM["order"]==2) $tmp .= $ford . $dord;
				else $tmp .= $dord . $ford;
				$fils[$fi++] = $tmp . '</tr>';
				$f_anz++;
				$gi++;
			}
			
			// Datei-Beschreibung der letzten Datei
			if( !empty($last_entry) && file_exists( $fullpath."/".$last_entry.".file" ) ) {
				$filedesc = join( "", file( $fullpath."/".$last_entry.".file" ) );
				$f_desc = "\n".'<tr class="desc line_' . ((($gi)%2)?"even":"odd") . '"><td align="center" valign="top" width="' . $w[0] . '"><img src="' . $icon["desc"] . '" border="0" alt="Beschreibung zu ' . $last_entry . '"></td><td colspan="' . ($cs-1) . '" class="filedesc">' . nl2br(strip_tags($filedesc, $PARAM["allowable_tags"])) . "</td></tr>\n";
				$f_desc .= '<tr><td colspan="' . $cs . '"><img src="' . $spacer . '" width="1" height="6" border="0"></td></tr>';
				$fils[$fi++] = $f_desc;
			}
		}
		
		echo '<table border="0" align="center" width="' . ($PARAM["width"]-30) . '" cellpadding="2" cellspacing="0">' . "\n";
		if ($PARAM["statistic"] || $dirdesc) echo '<tr><td colspan="' . $cs . '">' . "\n";
		if ($PARAM["statistic"]) echo '<table border="0" width="' . ($PARAM["width"]-35) . '" cellpadding="0" cellspacing="0"><tr><td valign="top" class="statistic"><b>Statistik:</b></td><td align="right" class="statistic">Ordner: ' . ($d_anz) . "<br>Dateien: " . $f_anz . "</td></tr></table>\n";
		if ($dirdesc) echo '<table border="0" width="' . ($PARAM["width"]-35) . '" cellpadding="0" cellspacing="0"><tr><td class="dirdesc">' . nl2br(strip_tags($dirdesc, $PARAM["allowable_tags"])) . "<br>&nbsp;</td></tr></table>\n";
		if ($PARAM["statistic"] || $dirdesc) echo '</td></tr>';
		
		// Ordner
		for($i=0;$i<count($dirs);$i++) {
			echo $dirs[$i]."\n";
		}
		// Dateien
		for($i=0;$i<count($fils);$i++) {
			echo $fils[$i]."\n";
		}
		
		// LEER
		if ($gi == 0) {
			$colspan = 3;
			if ($PARAM["show_sz"]) $colspan++;
			echo '<tr><td align="center" class="none" colspan="' . $colspan . '">[ Keine Elemente vorhanden ]</td></tr>';
		}
		
		echo '</table>';
	}


	/**
	 * Leifert das zur Extension gehoerige Icon
	 *
	 * @param string $entry
	 */
	public static function getIcon($entry) {
		global $icon;
		$path_parts = pathinfo($entry);
		$ext = $path_parts["extension"];
		$ret = '';
		foreach ($icon as $val) {
			$arr_ext = explode("|",$val["ext"]);
			foreach ($arr_ext as $exten) {
				if ($exten == strtolower($ext)) {
					$ret = '<img src="'.$val["path"].'" border="0" alt="'.strtoupper($exten).'-Datei">';
					break;
				}
			}
			if (!$ret && $icon["default"]) $ret = '<img src="'.$icon["default"].'" border="0" alt="'.strtoupper($ext).'-Datei">';
		}
		return $ret;
	}
	
	/**
	 * Gibt die Groesse der Datei formatiert zurueck!
	 *
	 * @param string $file
	 * @param bool $formated
	 */
	public static function get_Size($file, $formated=false) {
		if (!is_file($file)) return false;
		$size = @filesize($file);
		if (!$formated) return $size;
		if ($size < 1024) {
			$fsize = @number_format($size,0,',','.') . "&nbsp;&nbsp;&nbsp;B";
		} elseif ($size >= 1000000) {
			$fsize = @number_format($size/1048576,2,',','.') . "&nbsp;MB";
		} elseif ($size < 1048576) { //>
			$fsize = @number_format($size/1024,2,',','.') . "&nbsp;KB";
		}
		return $fsize;
	}
	
	/**
	 * Durchsucht das array vars nach dem suchbegriff $str
	 *
	 * @param string $str
	 * @param array $vars
	 */
	public static function a_search($str, $vars) {
		if (is_array($vars)) {
			foreach ($vars as $key => $val) {
				if (stristr($str, $val)) return true;
			}
			return false;
		}
	}
	
	/**
	 * sortiert die Ordner/Dateien-Arrays
	 *
	 * @param array $a
	 * @param array $b
	 */
	public static function a_sort($a, $b) {
		global $PARAM;
		$ret = 0;
		$myOrder = $PARAM["displayOrder"];
	
		if ($myOrder == 3 || $myOrder == 6) {
					if ($a["type"]=="d" && $b["type"]=="f") $ret =  1;
			elseif ($a["type"]=="f" && $b["type"]=="d") $ret = -1;
			# Zuruecksetzen auf Namenssortierung
			elseif ($a["type"]=="d") $myOrder = $myOrder-2;
		}
	
		switch ($myOrder) {
			// nach Name
			case 1:
			case 4:
				$ret = strcasecmp($a["name"], $b["name"]);
				break;
			// nach Datum
			case 2:
			case 5:
						if ($a["dt"] < $b["dt"] ) $ret =  1;
				elseif ($a["dt"] > $b["dt"] ) $ret = -1;
				else $ret = strcasecmp($a["name"], $b["name"]);
				break;
			// nach Groesse
			case 3:
			case 6:
						if ($a["sz"] > $b["sz"] ) $ret =  1;
				elseif ($a["sz"] < $b["sz"] ) $ret = -1;
				else $ret = strcasecmp($a["name"], $b["name"]);
				break;
		}
	
		#echo "$myOrder + $ret| ";
	
		// Reihenfolge umkehren...
		if ($myOrder > 3) $ret = ( $ret > 0 ? -1 : ( $ret < 0 ? 1 : 0 ) );
	
		#echo "$myOrder + $ret<br />";
		return $ret;
	}


	/**
	 * Fire a download of file $file
	 *
	 * @param string $file   Path to the downloadfile
	 * @return none
	 */
	public static function fileDownload($file){
		if (file_exists($file)) {
			$mime_type = self::getMime($file);
			
			header('Content-Description: File Transfer');
			header('Content-Type: ' . $mime_type);
			header('Content-Disposition: attachment; filename='.basename($file));
			header('Content-Transfer-Encoding: binary');
			header('Expires: 0');
			header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
			header('Pragma: public');
			header('Content-Length: ' . filesize($file));
			//ob_clean();
			//flush();
			readfile($file);
			exit;
		}
		return false;
	}
	
	/**
	 * Saves a message to the session
	 *
	 * @param string $string
	 * @return none
	 */
	public static function setMessage($string) {
		if (!isset($_SESSION["ztListDir"]["message"])) $_SESSION["ztListDir"]["message"] = array();
		$_SESSION["ztListDir"]["message"][] = $string;
	}
	
	/**
	 * Checks whether a message is saved or not
	 *
	 * @param none
	 * @return bool
	 */
	public static function isMessage() {
		return isset($_SESSION["ztListDir"]["message"]) && !empty($_SESSION["ztListDir"]["message"]);
	}
	
	/**
	 * Returns the messages saved in the session
	 *
	 * @param bool $joined
	 * @param bool $clean
	 * @return array
	 */
	public static function getMessage($joined=false, $clean=true) {
		if (!self::isMessage()) return null;
		$ret = $_SESSION["ztListDir"]["message"];
		if ($joined) $ret = join("<br />\n", $ret);
		if ($clean) {
			unset($_SESSION["ztListDir"]["message"]);
			$_SESSION["ztListDir"]["message"] = array();
		}
		return $ret;
	}
	
	/**
	 * Saves an error to the session
	 *
	 * @param string $string
	 * @return none
	 */
	public static function setError($string) {
		if (!isset($_SESSION["ztListDir"]["error"])) $_SESSION["ztListDir"]["error"] = array();
		$_SESSION["ztListDir"]["error"][] = $string;
	}
	
	/**
	 * Checks whether an error is saved or not
	 *
	 * @param none
	 * @return bool
	 */
	public static function isError() {
		return isset($_SESSION["ztListDir"]["error"]) && !empty($_SESSION["ztListDir"]["error"]);
	}
	
	/**
	 * Returns the Errors saved in the session
	 *
	 * @param bool $joined
	 * @param bool $clean
	 * @return array
	 */
	public static function getError($joined=false, $clean=true) {
		if (!self::isError()) return null;
		$ret = $_SESSION["ztListDir"]["error"];
		if ($joined) $ret = join("<br />\n", $ret);
		if ($clean) {
			unset($_SESSION["ztListDir"]["error"]);
			$_SESSION["ztListDir"]["error"] = array();
		}
		return $ret;
	}
	
	/**
	 * Shows a default 404 HTML-Page
	 *
	 * @param string $path
	 * @param string $message
	 * @return none
	 */
	public static function show404($path=null, $message=null) {
		if (!empty($path)) $path="$path ";
		if (!empty($message)) $message="<br />\n$message";
		
		echo <<<EOD
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL {$path}was not found on this server.{$message}</p>
<hr>
<address>Apache Server Port 80</address>
</body></html>
EOD;
		exit;
	}
	
	/**
	 * Redirect
	 *
	 * @param string $file
	 * @return none
	 */
	public static function redir2self($file=null) {
		global $PARAM;
		$uri = $PARAM["ztListDir_host"] . $PARAM["show_dir"];
		if (!empty($file)) $uri = $file;
		if (!isset($_SESSION["ztListDir"]["redirCounter"])) {
			$_SESSION["ztListDir"]["redirCounter"] = array();
			$_SESSION["ztListDir"]["redirCounter"]["next"] = 0;
			$_SESSION["ztListDir"]["redirCounter"]["history"] = array();
		}
		$_SESSION["ztListDir"]["redirCounter"]["next"]++;
		$_SESSION["ztListDir"]["redirCounter"]["history"][] = $uri;
		header("Location: $uri");
		exit;
	}
	
	/**
	 * Returns a MD5 hash of the given string $str
	 *
	 * @param string $str
	 * @return string
	 */
	public static function gID($str) {
		return hash("MD5", $str);
	}
	
	/**
	 * Returns an Array with Paths
	 * @param bool $top
	 */
	public static function getProtectedParentFolder($top=true) {
		global $PARAM;
		$ret = array();
		if (empty($path)) $path = $PARAM["show_dir"];
		$i=0;
		$checkPath = $PARAM["ztListDir_root"] . $path;
		while( !empty($checkPath) ) {
			if ($i > 20) break;
			if (is_file($checkPath . "/pass.dir")) {
				$ret[] = $checkPath;
				if (!$top) break;
			}
			$checkPath = dirname($checkPath);
			$i++;
		}
		
		return array_reverse($ret);
	}
	
	public static function getUsername() {
		$ret = null;
		if (self::isUser()) {
			return key($_SESSION["ztListDir"]["user"]);
		}
		return $ret;
	}
	
	/**
	 * Checks whether a user is logged in or not
	 *
	 * @param string $username
	 */
	public static function isUser($username=null) {
		$ret = isset($_SESSION["ztListDir"]["user"]) && !empty($_SESSION["ztListDir"]["user"]);
		if (!empty($username) && $ret) $ret = isset($_SESSION["ztListDir"]["user"][$username]) && !empty($_SESSION["ztListDir"]["user"][$username]);
		return $ret;
	}
	
	/**
	 *
	 *
	 * @return none
	 */
	public static function logOff() {
		unset($_SESSION["ztListDir"]["user"]);
		self::redir2self();
	}
	
	
	/**
	 * Enter description here ...
	 *
	 * @param string $path
	 * @param string $hostName
	 * @return string
	 */
	public static function getNavi($path) {
		global $PARAM;
		$ret = null;
		$link = array();
		
		// Anzuzeigende Ordner
		$arrDirs = explode("/", $PARAM["show_dir"]);
		// unnoetiges entfernen
		unset($arrDirs[0], $arrDirs[count($arrDirs)]);
		// erste Zeile Domain, alle weiteren Zeilen sind Ordner
		$link = array_merge(array($PARAM["ztListDir_host"]), array_values($arrDirs));
		
		// Slash oder Pfeil
		if ($PARAM["path_divider"] == 2) $divider = '<span class="icon-divider ui-icon ui-icon-triangle-1-e">&nbsp;</span>';
		else $divider = '/';
		
		// Link-String bauen
		$linkStr = null;
		for($i=0, $n=count($link); $i<$n; $i++) {
			if ($i < ($n-1)) $ret .= sprintf('<a href="%s/">%s</a>', $linkStr . $link[$i], $link[$i]);
			else $ret .= sprintf('<b>%s</b>', $link[$i]);;
			$linkStr .= $link[$i] . "/";
			if (isset($link[$i+1])) $ret .= $divider;
		}
		return $ret;
	}
	
	public static function getMime($filename) {
		$mime_types = array();
		if (file_exists(APACHE_MIME_TYPES_DIR . "mime.types.inc.php")) {
			require_once APACHE_MIME_TYPES_DIR . "mime.types.inc.php";
		}
		// default
		$ret = "application/octet-stream";
		
		// fileinfo
		$filename = basename($filename);
		$fileext = substr(strrchr($filename, '.'), 1);
		if (empty($fileext)) return $ret;
		
		if (!empty($mime_types[$fileext])) $ret = $mime_types[$fileext];
		
		return $ret;
	}
	
	public static function makeMimeArrayFile() {
		$mimeArray = self::get_mime_array();
		
		$lines  = sprintf("<?%s\n", "php");
		$lines .= sprintf('$%s = array('."\n", "mime_types");
		foreach ($mimeArray as $key => $val) {
			$lines .= sprintf("\t'%s' => '%s',\n", $key, $val);
		}
		$lines .= sprintf("\t'%s' => '%s'\n", "it_is_just", "an_empty_element");
		$lines .= sprintf(");\n?%s\n", ">");
		
		$ret = file_put_contents(APACHE_MIME_TYPES_DIR . "mime.types.inc.php", $lines);
		if ($ret !== false) return true;
		else return false;
	}
	
	private static function get_mime_array() {
		$mimeArray = array();
		$regex = "/([\w\+\-\.\/]+)\t+([\w\s]+)/i";
		$lines = @file(APACHE_MIME_TYPES_URL, FILE_IGNORE_NEW_LINES);
		if (empty($lines)) $lines = @file(APACHE_MIME_TYPES_DIR . "mime.types", FILE_IGNORE_NEW_LINES);
		if (!empty($lines)) {
			foreach($lines as $line) {
				if (substr($line, 0, 1) == '#') continue; // skip comments
				if (!preg_match($regex, $line, $matches)) continue; // skip mime types w/o any extensions
				$mime = $matches[1];
				$extensions = explode(" ", $matches[2]);
				foreach($extensions as $ext) $mimeArray[trim($ext)] = $mime;
			}
		}
		return ($mimeArray);
	}
	
}


?>